//
//  LXPageCollectonView.swift
//  LXPageView
//
//  Created by seven on 2017/12/22.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit

protocol LXPageCollectionViewDataSource: class {
    func numberOfSections(in pageCollectionView: LXPageCollectonView) -> Int
    func pageCollectionView(_ collectionView: LXPageCollectonView, numberOfItemsInSection section: Int) -> Int
    func pageCollectionView(_ pageCollectionView: LXPageCollectonView, _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
}

protocol LXPageCollectonViewDelegate: class {
    func pageCollectionView(_ collectionView: LXPageCollectonView, didSelectItemAt indexPath: IndexPath)
}

class LXPageCollectonView: UIView {

    weak var dataSource: LXPageCollectionViewDataSource?
    private var titles: [String]
    private var isTitleInTop: Bool
    private var layout: LXPageCollectionViewLayout
    private var style: LXTitleStyle
    private var collectionView: UICollectionView!
    private var pageControl: UIPageControl!
    private var titleView: LXTitleView!
    private var sourceIndexPath: IndexPath = IndexPath(item: 0, section: 0)
    
    init(frame: CGRect, titles: [String], style: LXTitleStyle, isTitleInTop: Bool, layout: LXPageCollectionViewLayout) {
        self.titles = titles
        self.isTitleInTop = isTitleInTop
        self.layout = layout
        self.style = style
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension LXPageCollectonView{
    private func setupUI() {
        //1.创建titleView
        let titleY = isTitleInTop ? 0 : bounds.height - style.titleHeight
        let titleFrame = CGRect(x: 0, y: titleY, width: bounds.width, height: style.titleHeight)
        titleView = LXTitleView(frame: titleFrame, titles: titles, style: style)
        titleView.backgroundColor = UIColor.randomColor()
        titleView.delegete = self
        addSubview(titleView)
        //2.创建UIPageControll
        let pageControlHeight: CGFloat = 20
        let pageControlY = isTitleInTop ? bounds.height - pageControlHeight : bounds.height - pageControlHeight - style.titleHeight
        let pageControlFrame = CGRect(x: 0, y: pageControlY, width: bounds.width, height: pageControlHeight)
        pageControl = UIPageControl(frame: pageControlFrame)
        pageControl.numberOfPages = 4
        pageControl.isEnabled = false
        pageControl.backgroundColor = UIColor.randomColor()
        addSubview(pageControl)
        //3.创建collectionView
        let collectionViewY = isTitleInTop ? style.titleHeight : 0
        collectionView = UICollectionView(frame: CGRect(x: 0, y: collectionViewY, width: bounds.width, height: bounds.height - style.titleHeight - pageControlHeight), collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPagingEnabled = true
        collectionView.backgroundColor = UIColor.randomColor()
        addSubview(collectionView)
    }
}

//MARK:- UIcollectionViewDatasource
extension LXPageCollectonView: UICollectionViewDataSource{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return dataSource?.numberOfSections(in: self) ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let itemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 0
        if section == 0 {
            pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1
        }
        return itemCount
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return dataSource!.pageCollectionView(self, collectionView, cellForItemAt: indexPath)
    }
    
    
}

//MARK:- UICollectionViewDelegate
extension LXPageCollectonView: UICollectionViewDelegate{
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewEndScroll()
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate{
            scrollViewEndScroll()
        }
    }
    
    private func scrollViewEndScroll(){
        //1.取出在屏幕中显示的cell
        let point = CGPoint(x: layout.sectionInset.left + 1 + collectionView.contentOffset.x, y: layout.sectionInset.top + 1)
        guard let indexPath = collectionView.indexPathForItem(at: point) else {return}
        
        //3.判断分组是否有发生改变
        if sourceIndexPath.section != indexPath.section {
            guard let itemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) else {return}
            //3.1设置titleView位置
            titleView.adjustTitleLabel(targetIndex: indexPath.section)
            //3.2记录最新的位置
            sourceIndexPath.section = indexPath.section
            pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1
        }
        //2.根据IndexPath设置pageControl
        pageControl.currentPage = indexPath.item / (layout.cols * layout.rows)
    }
}

//MARK:- LXTitleView代理
extension LXPageCollectonView: LXTitleViewDelegete{
    func titleView(_ titleView: LXTitleView, targetIndex: Int) {
        let indexPath = IndexPath(item: 0, section: targetIndex)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        collectionView.contentOffset.x -= layout.sectionInset.left
        
        guard let itemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) else {return}
        pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1
        pageControl.currentPage = indexPath.item / (layout.cols * layout.rows)
        sourceIndexPath.section = targetIndex
    }
}
//MARK:- 对外暴露方法
extension LXPageCollectonView{
    func register(cellClass: Swift.AnyClass?, identifier: String){
        collectionView.register(cellClass, forCellWithReuseIdentifier: identifier)
    }
    
    func register(nib: UINib?, identifier: String){
        collectionView.register(nib, forCellWithReuseIdentifier: identifier)
    }
}
